/**
 * Copyright (c) [2022] [yanyeori]
 * [yanyeori-service] is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.yanyeori.service.file.business.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yanyeori.framework.core.util.StringUtil;
import com.yanyeori.service.file.api.dto.FileDTO;
import com.yanyeori.service.file.business.config.OssConfig;
import com.yanyeori.service.file.business.service.OssFileService;
import com.yanyeori.service.file.business.util.FileServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * ALIYUN OSS文件存储
 *
 * @author chenkuan
 * @since 2022/9/29 13:32
 */
@Service
public class OssFileServiceImpl implements OssFileService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OssConfig ossConfig;

    /**
     * OSS文件上传接口
     *
     * @param file 上传的文件
     * @return 文件上传信息
     */
    @Override
    public FileDTO upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = FileServiceUtil.extractFilePath(fileName);
        String url = null;
        //创建OSSClient实例
        OSS ossClient = buildOSSClient();
        //调用oss实现上传，bucket名称+文件名称+输入流
        ossClient.putObject(ossConfig.getBucketName(), filePath, file.getInputStream());
        //关闭OSSClient
        ossClient.shutdown();
        logger.info("file[{}] upload to OSS success", fileName);
        if (ossConfig.isPublicRead()) {
            url = StringUtil.format("{}{}.{}/{}", ossConfig.getHttp(), ossConfig.getBucketName(), ossConfig.getEndpoint(), filePath);
        }
        return new FileDTO(fileName, filePath, url);
    }

    /**
     * 获取OSS文件下载链接
     *
     * @param filePath 文件路径
     * @return 访问地址
     */
    @Override
    public String getDownloadUrl(String filePath) {
        //创建OSSClient实例
        OSS ossClient = buildOSSClient();
        Date expiration = new Date(System.currentTimeMillis() + ossConfig.getUrlExpiration() * 1000);
        String url = ossClient.generatePresignedUrl(ossConfig.getBucketName(), filePath, expiration).toString();
        ossClient.shutdown();
        return url;
    }

    /**
     * 创建OSSClient实例
     */
    private OSS buildOSSClient() {
        return new OSSClientBuilder().build(ossConfig.getHttp() + ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
    }
}
